from decimal import Decimal
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView, ListAPIView

from goods.models import SKU, Goods
from meiduo_mail.utils.paginations import StandardResultsSetPagination
from .serializers import OrderSettlementSerializer, CommitOrderSerializer, ComentGoodsSerializer, \
    CommitCommentSerializer, OrderListSerializer
from .models import OrderGoods, OrderInfo
from users.models import User


class CommitOrderView(CreateAPIView):
    # 指定权限
    permission_classes = [IsAuthenticated]

    # 指定序列化器
    serializer_class = CommitOrderSerializer


class ListOrderView(ListAPIView):
    # 指定权限
    permission_classes = [IsAuthenticated]

    # 指定序列化器
    serializer_class = OrderListSerializer

    # 指定分页类
    paginator_class = StandardResultsSetPagination

    def get_queryset(self):
        user = self.request.user
        user_orders = OrderInfo.objects.filter(user_id=user.id).order_by('-create_time')
        return user_orders


class OrderSettlementView(APIView):
    """订单结算"""
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """获取"""
        user = request.user

        # 从购物车获取用户勾选结算的商品信息
        redis_conn = get_redis_connection('cart')
        redis_cart = redis_conn.hgetall('cart_%s' % user.id)
        cart_selected = redis_conn.smembers('selected_%s' % user.id)

        cart = {}
        for sku_id in cart_selected:
            cart[int(sku_id)] = int(redis_cart[sku_id])

        # 查询商品信息
        skus = SKU.objects.filter(id__in=cart.keys())
        for sku in skus:
            sku.count = cart[sku.id]

        # 运费
        freight = Decimal('10.00')
        # 创建序列化器时 instance参数可以传递
        serializer = OrderSettlementSerializer({'freight': freight, 'skus': skus})

        return Response(serializer.data)


class CommentGoodsView(APIView):
    '''商品评论界面展示'''
    permission_classes = [IsAuthenticated]  # 权限设置

    def get(self, request, order_id):
        # 获取订单商品信息
        order_goods = OrderGoods.objects.filter(order_id=order_id, is_commented=False)
        serializer = ComentGoodsSerializer(order_goods, many=True)
        return Response(serializer.data)


class CommitCommentView(APIView):
    '''保存评论'''
    permission_classes = [IsAuthenticated]  # 权限设置

    def post(self, request, order_id):
        # 获取sku
        sku = request.data.get('sku')
        order_goods = OrderGoods.objects.get(order_id=order_id, sku_id=sku)
        # 创建序列化器对象
        serializer = CommitCommentSerializer(instance=order_goods, data=request.data)
        # 校验
        serializer.is_valid(raise_exception=True)
        # 保存评论
        serializer.update(order_goods, serializer.validated_data)

        # SKU评论数叠加
        good_sku = SKU.objects.get(id=sku)
        good_sku.comments += 1
        good_sku.save()

        # Goods评论数叠加
        goods = Goods.objects.get(id=good_sku.goods_id)
        goods.comments += 1
        goods.save()

        # 获取订单商品信息,判断是否评论,如果全部评论,修改订单状态
        order_goods = OrderGoods.objects.filter(order_id=order_id).all()

        is_commented_list = []
        for good in order_goods:
            is_commented_list.append(good.is_commented)

        if False not in is_commented_list:
            # 修改订单状态
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT']).update(
                status=OrderInfo.ORDER_STATUS_ENUM['FINISHED'])

        return Response(serializer.data)


class ReadCommentView(APIView):
    '''展示评论'''

    def get(self, request, sku_id):
        # 查询有评论的商品信息
        skus = OrderGoods.objects.filter(sku_id=sku_id, is_commented=True)
        # 给每个商品添加username
        for sku_good in skus:
            order_info = OrderInfo.objects.get(order_id=sku_good.order_id)
            username = User.objects.get(id=order_info.user_id).username
            if sku_good.is_commented is True:
                username = username[0] + '*' * 5 + username[-1]
                sku_good.username = username

        serializer = CommitCommentSerializer(skus, many=True)
        return Response(data=serializer.data)
